<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleSearch"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <template style="width: 100%">
        <el-table :data="userList" style="width: 100%" border stripe>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="username" label="姓名" width="180">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="180">
          </el-table-column>
          <el-table-column prop="mobile" label="电话" width="180">
          </el-table-column>
          <el-table-column prop="role_name" label="角色" width="180">
          </el-table-column>
          <el-table-column prop="mg_state" label="状态" width="180">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="handleStateChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280px">
            <template slot-scope="scope">
              <el-tooltip
                :enterable="false"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                   @click="showEditDialog(scope.row)"
                ></el-button>
              </el-tooltip>

              <el-tooltip
                :enterable="false"
                effect="dark"
                content="删除"
                placement="top"
               
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                   @click="removeUserById(scope.row.id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                :enterable="false"
                effect="dark"
                content="分配角色"
                placement="top"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                 @click="setRole(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username" >
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
     <el-dialog
  title="分配权限"
  :visible.sync="setRoleDialogVisible"
  width="50%"
  @close="setRoleDialogClosed"
  >
  <div>
    <p>当前用户:{{userInfo.username}}</p>
    <p>当前角色:{{userInfo.role_name}}</p>
    <p>分配新角色:
      <el-select v-model="selectedRoleId" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select></p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRoles">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedRoleId:'',
      rolesList:[],
      userInfo:{},
      setRoleDialogVisible:false,
      editDialogVisible: false,
      editFormRules:{
         username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur",
          },
        ],

      },
      addFormRules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          {
            min: 6,
            max: 10,
            message: "长度在 6 到 10 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
          },
          {
            min: 1,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      editForm: {
        id:0,
        username: "",
        email: "",
        mobile:''
      },
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addDialogVisible: false,
      userList: [],
      total: 0,
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    removeUserById(id){
      
       this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
         
          
          this.$http.delete(`users/${id}`).then(res=>{
            console.log(res.data)
            if(res.data.meta.status===200){
               this.$message({
            type: 'success',
            message: '删除成功!'
          })
            }
            else
            {
              this.$message.error("删除失败")
            }
          })
          this.getUserList()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    editUser() {
      console.log(this.editForm)
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
        this.$http.put( `users/${this.editForm.id}`,{
          email:this.editForm.email,
          mobile:this.editForm.mobile
        }).then(res=>{
          if(res.data.meta.status===200){
             this.$message.success("修改用户信息成功")
           
            
          }else
          {
            this.$message.error("修改用户信息失败")
          }
        })
        } else {
          return this.$message.error("表单验证失败");
        }
      });
       this.getUserList()
      this.editDialogVisible=false
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    showEditDialog(userInfo) {
      // console.log(1)
      this.editForm.id=userInfo.id
      this.editDialogVisible = true;
      this.editForm.username=userInfo.username
      this.editForm.email=userInfo.email
      this.editForm.mobile=userInfo.mobile
    },
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          this.$http.post("users", this.addForm).then((res) => {
            console.log(res.data);
            if (res.data.meta.status === 201) {
              this.$message.success("添加用户成功");
            } else {
              this.$message.error("添加用户失败");
            }
          });
        } else {
          return this.$message.error("表单验证失败");
        }
      });
      this.addDialogVisible = false;
      this.getUserList();
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    getUserList() {
      this.$http.get("users", { params: this.queryInfo }).then((res) => {
        if (res.data.meta.status === 200) {
          // console.log("后执行")
          this.userList = res.data.data.users;

          this.total = res.data.data.total;
        } else {
          this.$message.error("获取用户列表失败");
        }
        
      });
      // console.log("先执行")
    },
    handleSizeChange(newpages) {
      this.queryInfo.pagesize = newpages;
      this.getUserList();
      // console.log(1)
    },
    handleCurrentChange(currentPage) {
      this.queryInfo.pagenum = currentPage;
      this.getUserList();
      // console.log(2)
    },
    handleStateChange(userinfo) {
      this.$http
        .put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.$message.success("更新状态成功");
          } else {
            userinfo.mg_state = !userinfo.mg_state;
            return this.$message.error("更新状态失败");
          }
        });
    },
    handleSearch() {
      this.getUserList();
    },
    allotRoles(){
      if(!this.selectedRoleId){
        this.$message.info("请选择分配角色")
        return
      }
      this.$http.put(`users/${this.userInfo.id}/role`,{
        rid:this.selectedRoleId
      }).then(res=>{
        if(res.data.meta.status===200){
          this.$message.success("分配角色成功")
          this.getUserList()
          this.setRoleDialogVisible=false
        }
        else{
          this.$message.error("分配角色失败")
          this.setRoleDialogVisible=false
        }
      })

    },
    setRole(user){
      this.userInfo=user
      this.$http.get(`roles`).then(res=>{
        if(res.data.meta.status===200){
          this.rolesList=res.data.data
        }
        else{
          this.$message.error("获取角色列表失败")
        }
      })
      this.setRoleDialogVisible=true

    },
    setRoleDialogClosed(){
      this.selectedRoleId="",
      this.userInfo={}
      this.setRoleDialogVisible=false
    }
  },
};
</script>

<style lang="less" scoped>
</style>

